package com.wenyl.linear.queue;

import lombok.Data;


/**
 * @author Swimming Dragon
 * @description: 链表实现队列
 * @date 2024年10月18日 11:52
 */
@Data
public class LinkedListQueue {
    // 队列头元素
    private LLQNode head;
    // 队列尾元素
    private LLQNode tail;
    // 元素个数
    private int length;
    public LinkedListQueue(){
        head = tail = null;
        length = 0;
    }
    /**
     * 从队尾入队
     * @param data 数据
     */
    public void offer(int data){
        LLQNode node = new LLQNode(data);
        if(isEmpty()){
            head = tail = node;
            length++;
            return;
        }
        tail.setNext(node);
        node.setPre(tail);
        tail = node;
        length++;
    }


    /**
     * 从队首出队,空队返回-1
     */
    public int poll(){
        if(isEmpty()){
            System.out.println("空队");
            return -1;
        }
        LLQNode ret= head;
        if(getLength() == 1){
            head = tail = null;
            length--;
            return ret.getData();
        }
        // 设置队首的下一个元素为新的队首
        LLQNode newHead = head.getNext();
        newHead.setPre(null);
        ret.setNext(null);
        head = newHead;
        length--;
        return ret.getData();

    }

    public boolean isEmpty(){
        return getLength() == 0;
    }

    public void print() {
        if(isEmpty()){
            System.out.println("空队遍历");
            return;
        }
        LLQNode currentNode = head;
        do{
            System.out.print(currentNode.getData()+" ");
            currentNode = currentNode.getNext();
        }while(currentNode != null);
        System.out.println();
    }

}
@Data
class LLQNode{
    private int data;
    private LLQNode pre;
    private LLQNode next;
    public LLQNode(int data){
        this.data = data;
        this.pre = null;
        this.next = null;
    }
}